# coding: utf-8

import json
import logging
import traceback

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

# from services.datamodel.product.models import mm_Product, mm_ProductPurchase, mm_AliPayTrade
from lib.alipay_v2 import utils as alipay
from services.datamodel.order.models import mm_Order
from apps.baselogic.handlers.product import BaseHandler

alipay_logger = logging.getLogger("alipay")


def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


class Handler:

    # @csrf_exempt
    # def handle_student_buy_product_notify(self, request):
    #
    #     clientIp = get_client_ip(request)
    #
    #     ret = alipay.notify_verify(request.POST)
    #     if not ret:
    #         alipay_logger.warn("!!got an invalid alipay notify from:%s" % clientIp)
    #         return
    #
    #     tradeno_yijiao = request.POST.get("out_trade_no")
    #     if not tradeno_yijiao:
    #         alipay_logger.error("!!got an alipay notify from:%s,but no out_trade_no field in request" % clientIp)
    #         return HttpResponse('success')
    #
    #     #  返回支付状态
    #     trade_status = request.POST.get("trade_status")
    #     if not trade_status:
    #         alipay_logger.error("!!got an alipay notify from:%s,but no trade_status field in request" % clientIp)
    #         return HttpResponse('success')
    #
    #     if trade_status not in ['TRADE_SUCCESS', "TRADE_FINISHED"]:
    #         alipay_logger.error(
    #             "!!got an alipay notify from:%s,but trade_status field is not
    #             TRADE_SUCCESS or TRADE_FINISHED" % clientIp)
    #         return HttpResponse('success')
    #
    #     tradeno_ali = request.POST.get("trade_no")
    #     if not tradeno_ali:
    #         alipay_logger.error("!!got an alipay notify from:%s,but no trade_no field in request" % clientIp)
    #         return HttpResponse('success')
    #
    #     userId, _, productType, str_productids, str_ppis = tradeno_yijiao.split("_")
    #
    #     quantity = request.POST.get("quantity")
    #     if not quantity:
    #         alipay_logger.error("!!got an alipay notify from:%s,but no quantity field in request" % clientIp)
    #         return HttpResponse('success')
    #
    #     total_fee = request.POST.get("total_fee")
    #     if not total_fee:
    #         alipay_logger.error("!!got an alipay notify from:%s,but no total_fee field in request" % clientIp)
    #         return HttpResponse('success')
    #
    #     notify_time = request.POST.get("notify_time")
    #     buyer_email = request.POST.get("buyer_email")
    #     buyer_id = request.POST.get("buyer_id")
    #
    #     alipay_logger.info(
    #         "got an alipay notify : tradeno_yijiao:%s|tradeno_ali:%s|trade_status:%s|buyer_email:%s|buyer_id:%s" % \
    #         (tradeno_yijiao, tradeno_ali, trade_status, buyer_email, buyer_id))
    #
    #     mm_AliPayTrade.filter(tradeno_yijiao=tradeno_yijiao, total_fee=total_fee).update(
    #         deal_status=mm_AliPayTrade.TRADE_STATUS_PAYED,
    #         tradeno_ali=tradeno_ali,
    #         notifytime=notify_time,
    #         buyer_id=buyer_id,
    #         buyer_email=buyer_email)
    #     trades = mm_AliPayTrade.filter(tradeno_yijiao=tradeno_yijiao, total_fee=total_fee)
    #     if trades:
    #         trade = trades[0]
    #         params = json.loads(trade.details)
    #     else:
    #         return HttpResponse('success')
    #     coupon_id = params.get('coupon_id')
    #     order_detail = json.loads(trade.details)['order_detail']
    #     producttype = int(productType)
    #     if producttype == mm_Product.PRODUCT_TYPE_YJMEMEBER:  # 亿教课堂产品
    #         try:
    #             mm_ProductPurchase.purchaseProductByAliAndWx(userId=userId,
    #                                                          order_detail=order_detail,
    #                                                          quantity=quantity,
    #                                                          tradeno_yijiao=tradeno_yijiao,
    #                                                          tradeno_pd_no=tradeno_ali,
    #                                                          coupon_id=coupon_id,
    #                                                          buyer_user_id=params.get('buyer_id', 0),
    #                                                          )
    #
    #             # PaymentHandler.handleMembershipProductSuccessfulPurchased(int(userId),
    #             #                                                           str_productids,
    #             #                                                           tradeno_yijiao,
    #             #                                                           str_ppis
    #             #                                                           )
    #         except:
    #             alipay_logger.error('purchaseProductByAli exception:\n%s' % traceback.format_exc())
    #
    #     elif producttype in [mm_Product.PRODUCT_TYPE_ACTUAL, mm_Product.PRODUCT_TYPE_PROXY,
    #                          mm_Product.PRODUCT_TYPE_COMPANY, mm_Product.PRODUCT_TYPE_REAL]:
    #         try:
    #             mm_ProductPurchase.purchase_product_actual_by_ali_and_wechat(user_id=userId,
    #                                                                          order_detail=order_detail,
    #                                                                          quantity=1,
    #                                                                          tradeno_yijiao=tradeno_yijiao,
    #                                                                          trade_address=params['address'],
    #                                                                          trade_phone=params['phone'],
    #                                                                          trade_nickname=params['nickname'],
    #                                                                          province_code=params['province_code'],
    #                                                                          city_code=params['city_code'],
    #                                                                          district_code=params['district_code'],
    #                                                                          tradeno_paychannel=trade.tradeno_ali,
    #                                                                          product_type=producttype,
    #                                                                          paymenttype=1,
    #                                                                          invite_code=params.get('invite_code'),
    #                                                                          buyer_user_id=params.get('buyer_id', 0),
    #                                                                          )
    #         except:
    #             alipay_logger.error('purchaseProductByAli exception:\n%s' % traceback.format_exc())
    #
    #     return HttpResponse('success')

    @csrf_exempt
    def handle_ali_mobile_notify(self, request):
        """
        支付宝移动端回调文档 https://opendocs.alipay.com/open/204/105301
        :param request:
        :return:
        """

        clientIp = get_client_ip(request)

        ret = alipay.notify_verify(request.POST)
        if not ret:
            alipay_logger.warning("!!got an invalid alipay notify from:%s" % clientIp)
            return HttpResponse()

        tradeno_yijiao = request.POST.get("out_trade_no")
        if not tradeno_yijiao:
            alipay_logger.error("!!got an alipay notify from:%s,but no out_trade_no field in request" % clientIp)
            return HttpResponse()

        # 返回支付状态
        trade_status = request.POST.get("trade_status")
        if not trade_status:
            alipay_logger.error("!!got an alipay notify from:%s,but no trade_status field in request" % clientIp)
            return HttpResponse()

        if trade_status not in ['TRADE_SUCCESS', "TRADE_FINISHED"]:
            alipay_logger.error("!!got an alipay notify from:%s,but trade_status field is not TRADE_SUCCESS or "
                                "TRADE_FINISHED" % clientIp)
            return HttpResponse('success')

        tradeno_ali = request.POST.get("trade_no")
        if not tradeno_ali:
            alipay_logger.error("!!got an alipay notify from:%s,but no trade_no field in request" % clientIp)
            return HttpResponse()

        quantity = request.POST.get("quantity", 1)

        total_fee = request.POST.get("total_amount")  # wni: 2位小数，单位元
        if not total_fee:
            alipay_logger.error("!!got an alipay notify from:%s,but no total_amount field in request" % clientIp)
            return HttpResponse()

        notify_time = request.POST.get("notify_time")
        buyer_email = request.POST.get("buyer_logon_id")  # 支付宝账号，手机号或者邮箱
        buyer_id = request.POST.get("buyer_id")

        alipay_logger.info(
            "got an alipay notify : tradeno_yijiao:%s|tradeno_ali:%s|trade_status:%s|buyer_email:%s|buyer_id:%s" %
            (tradeno_yijiao, tradeno_ali, trade_status, buyer_email, buyer_id))

        # userid, _, producttype, str_productids, str_ppis = tradeno_yijiao.split("_")

        # mm_AliPayTrade.filter(tradeno_yijiao=tradeno_yijiao, total_fee=total_fee).update(
        #     deal_status=mm_AliPayTrade.TRADE_STATUS_PAYED,
        #     tradeno_ali=tradeno_ali,
        #     notifytime=notify_time,
        #     buyer_id=buyer_id,
        #     buyer_email=buyer_email)
        trade = mm_Order.filter(order_no=tradeno_yijiao, charge=int(float(total_fee)*100)).first()
        if trade:
            # trade.status = BaseHandler.TRADE_STATUS_PAID
            # trade.save()
            mm_Order.unproxybycard(trade)
        else:
            alipay_logger.warning("!!got an alipay notify from:%s, cannot find right order_no and charge" % clientIp)
            return HttpResponse()
        # elif producttype in [mm_Product.PRODUCT_TYPE_ACTUAL, mm_Product.PRODUCT_TYPE_PROXY,
        #                      mm_Product.PRODUCT_TYPE_COMPANY, mm_Product.PRODUCT_TYPE_REAL]:
        #     try:
        #         mm_ProductPurchase.purchase_product_actual_by_ali_and_wechat(user_id=int(userid),
        #                                                                      order_detail=order_detail,
        #                                                                      quantity=1,
        #                                                                      tradeno_yijiao=tradeno_yijiao,
        #                                                                      trade_address=params['address'],
        #                                                                      trade_phone=params['phone'],
        #                                                                      trade_nickname=params['nickname'],
        #                                                                      province_code=params['province_code'],
        #                                                                      city_code=params['city_code'],
        #                                                                      district_code=params['district_code'],
        #                                                                      tradeno_paychannel=trade.tradeno_ali,
        #                                                                      product_type=producttype,
        #                                                                      paymenttype=1,
        #                                                                      invite_code=params.get('invite_code'),
        #                                                                      buyer_user_id=params.get('buyer_id',
        #                                                                                               0),
        #                                                                      )
        #     except:
        #         alipay_logger.error('purchaseProductByAli exception:\n%s' % traceback.format_exc())

        return HttpResponse('success')

    @csrf_exempt
    def handle_teacher_withdraw_notify_notify(self, request):

        # print 'get handle_teacher_withdraw_notify_notify'
        # clientIp = get_client_ip(request)

        # ret = alipay.notify_verify(request.POST)
        # if not ret:
        #     alipay_logger.warn("!!got an invalid alipay notify from:%s" % clientIp)
        #     return
        return HttpResponse('success')


alipay_handler = Handler()
